package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cndw.kungfu.comm.AccessInspection;
import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsChat;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.disciple.PlayerMartial;
import com.cndw.kungfu.model.disciple.domain.Disciple;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.pvp.api.WarApiClient;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 聊天
 * 
 * @author fantadust
 * @date 2011-4-26 下午03:40:37
 */
@Controller
public class ChatController {

	/**
	 * 发送聊天
	 * 
	 * @param session
	 * @param sendMap
	 */
	public ResponseMessage sendMessage(Session session, Map<String, Object> sendMap) {
		long playerId = session.getUid();
		String msg = StringProcesser.removeHtml(String.valueOf(sendMap.get("message")).trim());
		int type = sendMap.containsKey("type") ? (Integer) sendMap.get("type") : ConstantsChat.Chat_Scene;

		if (msg == null || msg.length() == 0 || type == ConstantsChat.Chat_System) {// 判断类型意义不大.方法内部只支持基本聊天
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		boolean isHaved = false;
		if (type == ConstantsChat.Chat_Speaker) {
			isHaved = player.getPlayerBoxs().isHaveGoods(GoodsEffectConfig.chatSpeakerGoodsId);
			if (!isHaved && player.getGoldAll() < ConstantsModel.chatSpeakerGold) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
			}
		}
		int currentTime = TimeProcesser.getUnixTime();
		if (ConstantsConfig.isInspectComm(Constants.inspectChatLevel) && player.getLevel() < 35 && !AccessInspection.isGmInstructor(player.getAccountName())
				&& currentTime > ConstantsConfig.getSysCgOpenTime() + 86400 * 3) {
			if (type == ConstantsChat.Chat_World || type == ConstantsChat.Chat_Private || type == ConstantsChat.Chat_Scene) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.level", 35));
			}
		}

		if (msg.getBytes(Constants.charset).length > ConstantsConfig.getChatLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.overflow"));
		}

		if (type != ConstantsChat.Chat_Speaker && ConstantsConfig.getChatIntervalSeconds() > 0) {
			if (currentTime < player.getDataInfo().getLastChatTime() + ConstantsConfig.getChatIntervalSeconds()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.interval", ConstantsConfig.getChatIntervalSeconds()));
			}
			player.getDataInfo().setLastChatTime(currentTime);
		}

		boolean hidden = AccessInspection.isChatLockAcc(player.getAccountName());
		if (hidden) {

		} else {
			if (AccessInspection.checkChat(playerId)) {
				if (player.getLevel() >= 20) {
					String lockTime = TimeProcesser.getDateByUnixTime(AccessInspection.chatLockTime(playerId));
					return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.lockbytime", lockTime));
				} else {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.restricted"));
				}
			}
			if (CommInspection.checkSpam(player, msg)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.qq"));
			}
			if (AccessInspection.isForbidChat(player, msg)) {
				if (player.getLevel() >= 20) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.ad"));
				} else {
					return null;
				}
			}
			msg = CommInspection.checkFilter(player, msg);
			if (msg == null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.qq"));
			}
		}

		String message = WordProcesser.filterWorlds(msg);
		if (type == ConstantsChat.Chat_Speaker && !msg.equals(message)) {// 喇叭聊天，含有敏感词时返回提示
			return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.badword"));
		}

		if (type == ConstantsChat.Chat_Private) {
			if (!sendMap.containsKey("receiveId") || hidden) {// 隐藏聊天
				return null;
			}
			String obj = sendMap.get("receiveId").toString();
			long receiveId = Double.valueOf(obj).longValue();
			if (receiveId == session.getUid()) {
				return null;
			}
			if (!Context.getPlayerServer().isOnline(receiveId)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.sendmessage.offline"));
			}

			player.getDataInfo().setLastTalk(receiveId);

			Player targetPlayer = Context.getPlayerServer().getByPlayerId(receiveId);
			targetPlayer.getDataInfo().setLastTalk(playerId);

			ChatMain.privateMessage(message, player, receiveId);
		} else {
			if (type == ConstantsChat.Chat_Speaker) {

				if (isHaved) {
					player.getPlayerBoxs().costGoods(GoodsEffectConfig.chatSpeakerGoodsId, 1);
				} else {
					player.alterGoldAll(-ConstantsModel.chatSpeakerGold);
					LogServer.costEventLog(session.getUid(), ConstantsModel.chatSpeakerGold, ConstantsCost.chatSpeaker);
				}
				player.commitSync();
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(GoodsEffectConfig.chatSpeakerGoodsId);
				LogServer.recordLog(player, ConstantsLog.gold, 50006, isHaved, isHaved ? 0 : ConstantsModel.chatSpeakerGold, goodsMode.getName(), isHaved ? 1
						: 0);
			}
			ChatMain.sendMessage(type, message, player, hidden);
		}

		QQDC.getInstance().logClick(player, LogFieldType.chat);

		if (type == ConstantsChat.Chat_Speaker) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("gold", player.getGold());
			map.put("goldBing", player.getGoldBing());
			return ResponseMessage.getSuccMessage(map);
		}
		return null;
	}

	/**
	 * 显示装备信息...
	 * 
	 * @param session
	 * @param type
	 * @param targetId
	 * @return
	 */
	public ResponseMessage getChatInfo(Session session, long targetPlayerId, int type, String idP1, String idP2) {
		Player targetPlayer = Context.getPlayerServer().getByPlayerId(targetPlayerId);
		if (targetPlayer == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
		}
		Map<String, Object> map = new HashMap<String, Object>(2);
		if (type == 1) {
			PlayerBoxs playerBoxs = targetPlayer.getPlayerBoxs();
			long id1 = Long.valueOf(idP1);// 物品数据库id
			int id2 = Integer.valueOf(idP2);// 背包id
			Goods goods = playerBoxs.get(id2);
			if (goods == null || (id1 > 0 && goods.getId() != id1)) {
				goods = playerBoxs.getBySearcheId(id1);
			}
			if (goods == null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
			}
			map.put("goods", goods.toGoodsVO());
		} else if (type == 3) {
			PlayerBoxs playerBoxs = targetPlayer.getPlayerBoxs();
			int id1 = Integer.valueOf(idP1);// 物品id
			int id2 = Integer.valueOf(idP2);// 背包id
			Goods goods = playerBoxs.get(id2);
			if (goods == null || (id1 > 0 && goods.getGoodsId() != id1)) {
				goods = playerBoxs.getBySearcheGoodsId(id1);
			}
			if (goods == null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
			}
			map.put("goods", goods.toGoodsVO());

		} else if (type == 2) {
			PlayerMartial playerMartial = Context.getDiscipleServer().getByPlayerId(targetPlayerId);
			if (playerMartial == null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
			}
			int targetId = Integer.valueOf(idP1);
			Disciple disciple = playerMartial.getDiscipleById(targetId);
			if (disciple == null) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
			}
			map.put("disciple", disciple.toVO());
		} else {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.info.err"));
		}

		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossPlayer(Session session, int serverId, long targetId, int type) {
		return ResponseMessage.getSuccMessage(WarApiClient.crossPlayer(serverId, targetId, type));

	}

	public ResponseMessage chatShield(Session session, long targetId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Player target = Context.getPlayerServer().getByPlayerId(targetId);
		if (target == null) {
			return null;
		}

		int hour = 0;
		if (AccessInspection.isGmInstructor(player.getAccountName()) && ConstantsConfig.isInspectComm(Constants.inspectShieldFlag)) {
			hour = 1;
		} else if (AccessInspection.isGmAcc(session)) {
			hour = 12;
		}

		if (hour > 0 && target.getDataInfo().intDataGet(ConstantsIntKey.payCash) == 0) {
			if (target.getLevel() <= 20) {
				List<String> hids = ConstantsConfig.getSysLockChatAcc();
				if (!hids.contains(target.getAccountName())) {
					hids.add(target.getAccountName());
					LogUtil.getMain().info("chathidden acc " + target.getAccountName() + " on " + session.getAccountName());
				}
			} else if (hour == 12 && ConstantsConfig.isInspectComm(Constants.inspectShieldFlag)) {
				AccessInspection.addChatLock(targetId, hour * 3600);
				LogUtil.getMain().info("chatlock acc " + target.getAccountName() + " on " + session.getAccountName() + " " + hour);
			}
		}
		return null;
	}

}
